package com.liush.bookstore.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liush.bookstore.config.Result;
import com.liush.bookstore.mapper.BookMapper;
import com.liush.bookstore.mapper.CartMapper;
import com.liush.bookstore.model.Book;
import com.liush.bookstore.model.Cart;
import com.liush.bookstore.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/*
 * 购物车控制层
 * */
@Slf4j
@Controller
public class CartController {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private BookMapper bookMapper;

    //跳转购物车界面
    @RequestMapping("/cart")
    public String cart() {
        return "/cart/cart.html";
    }

    //添加商品到购物车
    @RequestMapping("/addCart")
    @ResponseBody
    public Object addCart(@RequestParam(name = "id", required = true) Integer id,
                          HttpServletRequest request) {
        //用户未登录无法向购物车添加商品
        User user = (User) request.getSession().getAttribute("user");
        if (user == null || user.equals("")) {
            return Result.error("请您先登录后添加!");
        }
        //根据书本id获取要添加的书本全部信息
        Book book = bookMapper.selectById(id);
        //根据书本id查询是否已添加至购物车
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getBook, id);
        Cart c = cartMapper.selectOne(queryWrapper);
        int num = 0;
        if (c == null || c.equals("")) {
            Cart cart = new Cart();
            cart.setBook(book.getId());
            cart.setBookname(book.getBookname());
            cart.setBookimg(book.getBookimg());
            cart.setPrice(book.getPrice());
            cart.setUser(user.getId());
            //如果该书本没有添加购物车，则购买数量设置为1
            cart.setBuycount(1);
            num = cartMapper.insert(cart);
        } else {
            //如果该书本已添加至购物车，则购买数量+1
            c.setBuycount(c.getBuycount() + 1);
            num = cartMapper.updateByPrimaryKey(c);
        }
        if (num != 1) {
            return Result.error(id + "：《" + book.getBookname() + "》添加失败!");
        }
        return Result.success(id + "：《" + book.getBookname() + "》添加成功!");
    }

    //用Thymeleaf实现购物车页面显示
    /*@RequestMapping("/cart")
    public String cart(HttpServletRequest request, Model model) {
        //根据登录用户id获取购物车信息
        User user = (User) request.getSession().getAttribute("user");
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUser, user.getId());
        List<Cart> carts = cartMapper.selectList(queryWrapper);
        model.addAttribute("carts", carts);
        //获取购物车商品总数量和总价格
        int totalCount = 0;
        double totalPrice = 0;
        for (int i = 0; i < carts.size(); i++) {
            Cart cart = carts.get(i);
            totalCount += cart.getBuycount();
            totalPrice += cart.getPrice() * cart.getBuycount();
        }
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("totalPrice", totalPrice);
        return "/cart/cart.html";
    }*/

    //用Vue实现购物车页面显示
    @ResponseBody
    @RequestMapping("/selectCart")
    public Object selectCart(HttpServletRequest request) {
        //根据登录用户id获取购物车信息
        User user = (User) request.getSession().getAttribute("user");
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUser, user.getId());
        List<Cart> carts = cartMapper.selectList(queryWrapper);
        //获取购物车商品总数量和总价格
        int totalCount = 0;
        double totalPrice = 0;
        for (int i = 0; i < carts.size(); i++) {
            Cart cart = carts.get(i);
            totalCount += cart.getBuycount();
            totalPrice += cart.getPrice() * cart.getBuycount();
        }
        //用map集合封装三组信息
        HashMap<String, Object> cartMap = new HashMap<>();
        cartMap.put("carts", carts);
        cartMap.put("totalCount", totalCount);
        cartMap.put("totalPrice", totalPrice);
        return cartMap;
    }

    //购物车加减商品数量更新页面内容
    @ResponseBody
    @RequestMapping("/updateCart")
    public Object updateCart(@RequestParam(name = "id", required = true) Integer id,
                             @RequestParam(name = "buyCount", required = true) Integer buyCount) {
        Cart cart = cartMapper.selectById(id);
        int num = 0;
        if (buyCount == 0 || buyCount.equals("") || buyCount == null) {
            num = cartMapper.deleteById(id);
        } else {
            cart.setBuycount(buyCount);
            num = cartMapper.updateById(cart);
        }
        if (num != 1) {
            return Result.error("购物车更新失败!请稍后再试!");
        }
        return Result.success("购物车更新成功!");
    }

    //删除选中id的购物车数据
    @ResponseBody
    @RequestMapping("/delCart")
    public Object delCart(@RequestParam(name = "id", required = true) Integer id) {
        int num = cartMapper.deleteById(id);
        if (num != 1) {
            return Result.error("删除失败!请稍后再试!");
        }
        return Result.success("删除成功!");
    }

    //删除购物车所有数据
    @RequestMapping("/delCarts")
    public Object delCarts(HttpServletRequest request) {
        //用户未登录无法向购物车添加商品
        User user = (User) request.getSession().getAttribute("user");
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUser, user.getId());
        cartMapper.delete(queryWrapper);
        return "redirect:/cart";
    }

    //跳转结账页面
    @RequestMapping("/checkout")
    public String checkout() {
        return "/cart/checkout.html";
    }
}
